<?php
/**
 * Created by PhpStorm.
 * User: dev
 * Date: 5/9/2014
 * Time: 3:18 PM
 */
class Categories extends Eloquent {

    public static $table = 'categories';
    public static $key = 'id';



    function __construct(){
        parent::__construct();

    }

    public static function findPK($id){
        if($id){
            if(Cache::get("categories_pk_".$id)){
                return Cache::get("categories_pk_".$id);
            }
            $result = DB::table('categories')->where('id', '=', $id)->first();
            Cache::put("categories_pk_".$id , $result,60*24*30);
            return $result;
        }
    }

    public static function parent($pid=0){
        if(Cache::get("categories_parent_".$pid)){
            return Cache::get("categories_parent_".$pid);
        }
        $result = DB::table('categories')->where('parent_id', '=', $pid)->get();
          Cache::put("categories_parent_".$pid,$result,60*24*30);
        return $result;
    }

    public static function child($pid = 0 ){
        if(Cache::get("categories_child_".$pid)){
            return Cache::get("categories_child_".$pid);
        }
        $result = DB::table('categories')->where('parent_id', '=', $pid)->take(50);
        if($result){
            Cache::put("categories_child_".$pid,$result,60*24*30);
            return $result;
        }
    }

    public static function total(){
        if(Cache::get("categories_total")){
            return Cache::get("settings_total");
        }
        $count = Categories::count();
        Cache::put("settings_total",$count,60*24*30);
        return $count;
    }




    public static function html_link($pid=null, $limit=3){
        if(!is_null($pid)){
            if(Cache::get("categories_link")){
                $cat =  Cache::get("categories_link");
            }else{
                $cat = DB::table('categories')->where('parent_id', '=', $pid)->take($limit)->get();
                Cache::put("categories_link",$cat,60*24*30);
            }

            $link = '';
            foreach ($cat as $cat){
                $url = Location::get().'/'.$cat->slug;
                $link.="<a class='' href='$url' title='$cat->name'> ". Str::limit($cat->name,12)." </a>, ";
            }

            //$link =  Str::limit(strip_tags($link), 50);

            $length = strlen(trim($link));
            $link = substr_replace($link, '', $length - 1, $length);
            return $link;

        }
    }
    
    public static function breadcrumb($id=0){
    	$r = Hierarchy::get_ancestors('categories', $id);
    	return $r;
    }
}